<template>
  <div class="app-container">
    <!-- 试卷基本信息区域 -->
    <div class="paper-info">
      <h1 class="paper-title">{{ paper.paperName }}</h1>
      <div class="paper-metadata">
        <div class="metadata-item">
          <span>总分：</span>
          <span class="score-value">{{ paper.totalScore }}分</span>
        </div>
        <div class="metadata-item">
          <span>题目数：</span>
          <span>{{ paper.number || allQuestions.length }}题</span>
        </div>
        <div class="metadata-item">
          <span>考试时长：</span>
          <span>{{ paper.duration }}分钟</span>
        </div>
      </div>
      <!-- 倒计时计时器 -->
      <div class="timer-container">
        <div class="timer" :class="{'timer-warning': remainingTime <= warningTime}">
          <i class="el-icon-alarm-clock"></i>
          <span class="time-text">剩余时间：{{ formatTime(remainingTime) }}</span>
        </div>
      </div>
    </div>

    <!-- 试卷内容区域 -->
    <div class="paper-content" v-loading="loading">
      <!-- 各题型分类显示 -->
      <!-- 单选题 -->
      <div v-if="singleChoiceQuestions.length > 0" class="question-section">
        <div class="section-title">一、单选题（共{{ singleChoiceQuestions.length }}题，共{{ singleChoiceTotal }}分）</div>
        <div v-for="(question, index) in singleChoiceQuestions" :key="question.questionId" class="question-item">
          <div class="question-content">
            <div class="question-title">
              <span class="question-index">{{ index + 1 }}.</span>
              <span class="question-type">[单选题]</span>
              <span class="question-score">({{ question.questionScore }}分)</span>
            </div>
            <div class="question-text" v-html="question.questionContent"></div>
            <div class="options-container">
              <div class="options-list">
                <div v-for="(option, optIndex) in question.options" :key="optIndex" class="option-item">
                  <el-radio v-model="question.selectedAnswer" :label="option.optionKey">
                    <span class="option-key">{{ option.optionKey }}.</span>
                    <span class="option-content" v-html="option.optionContent"></span>
                  </el-radio>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 多选题 -->
      <div v-if="multiChoiceQuestions.length > 0" class="question-section">
        <div class="section-title">二、多选题（共{{ multiChoiceQuestions.length }}题，共{{ multiChoiceTotal }}分）</div>
        <div v-for="(question, index) in multiChoiceQuestions" :key="question.questionId" class="question-item">
          <div class="question-content">
            <div class="question-title">
              <span class="question-index">{{ index + 1 }}.</span>
              <span class="question-type">[多选题]</span>
              <span class="question-score">({{ question.questionScore }}分)</span>
            </div>
            <div class="question-text" v-html="question.questionContent"></div>
            <div class="options-container">
              <div class="options-list">
                <el-checkbox-group v-model="question.selectedAnswers">
                  <div v-for="(option, optIndex) in question.options" :key="optIndex" class="option-item">
                    <el-checkbox :label="option.optionKey">
                      <span class="option-key">{{ option.optionKey }}.</span>
                      <span class="option-content" v-html="option.optionContent"></span>
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- A/B判断题 -->
      <div v-if="judgmentQuestions.length > 0" class="question-section">
        <div class="section-title">三、判断题（共{{ judgmentQuestions.length }}题，共{{ judgmentTotal }}分）</div>
        <div v-for="(question, index) in judgmentQuestions" :key="question.questionId" class="question-item">
          <div class="question-content">
            <div class="question-title">
            <span class="question-index">{{ index + 1 }}.</span>
              <span class="question-type">[判断题]</span>
              <span class="question-score">({{ question.questionScore }}分)</span>
          </div>
            <div class="question-text" v-html="question.questionContent"></div>
          <div class="options-container">
            <el-radio-group v-model="answers[question.questionId]">
              <el-radio label="A" class="option-row">
                <span class="option-label">A.</span>
                <span class="option-content">正确</span>
              </el-radio>
              <el-radio label="B" class="option-row">
                <span class="option-label">B.</span>
                <span class="option-content">错误</span>
              </el-radio>
            </el-radio-group>
            </div>
          </div>
        </div>
      </div>

      <!-- 填空题 -->
      <div v-if="fillBlankQuestions.length > 0" class="question-section">
        <div class="section-title">四、填空题（共{{ fillBlankQuestions.length }}题，共{{ fillBlankTotal }}分）</div>
        <div v-for="(question, index) in fillBlankQuestions" :key="question.questionId" class="question-item">
          <div class="question-content">
            <div class="question-title">
            <span class="question-index">{{ index + 1 }}.</span>
              <span class="question-type">[填空题]</span>
              <span class="question-score">({{ question.questionScore }}分)</span>
            </div>
            <div class="question-text" v-html="processBlankQuestion(question.questionContent, question.questionId)"></div>
          </div>
        </div>
      </div>

      <!-- 简答题 -->
      <div v-if="essayQuestions.length > 0" class="question-section">
        <div class="section-title">五、简答题（共{{ essayQuestions.length }}题，共{{ essayTotal }}分）</div>
        <div v-for="(question, index) in essayQuestions" :key="question.questionId" class="question-item">
          <div class="question-content">
            <div class="question-title">
            <span class="question-index">{{ index + 1 }}.</span>
              <span class="question-type">[简答题]</span>
              <span class="question-score">({{ question.questionScore }}分)</span>
          </div>
            <div class="question-text" v-html="question.questionContent"></div>
          <div class="essay-answer">
            <QuillEditor
              v-model:content="answers[question.questionId]"
              content-type="html"
              theme="snow"
              toolbar="full"
              :options="editorOptions"
            />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作区域 -->
    <div class="paper-footer">
      <el-button type="primary" @click="submitAnswer" :loading="submitting">提交试卷</el-button>
      <el-button type="info" @click="saveProgress" :loading="saving">保存进度</el-button>
    </div>

    <!-- 提交确认对话框 -->
    <el-dialog
      title="确认提交"
      v-model="submitDialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <span>确定要提交试卷吗？提交后将无法继续修改。</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="submitDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmSubmit" :loading="submitting">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 自动提交提示对话框 -->
    <el-dialog
      title="考试时间结束"
      v-model="autoSubmitDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <span>考试时间已结束，系统将自动提交您的答卷。</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="confirmAutoSubmit" :loading="submitting">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onBeforeUnmount, watch, nextTick, getCurrentInstance } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getPaperForExam, saveAnswerProgress, submitExamAnswer, getAnswerProgress, getServerTime, getExamSubmitStatus } from '@/api/manage/answer';
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import useUserStore from '@/store/modules/user'

export default {
  name: "Answer",
  components: {
    QuillEditor
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const paperId = ref(route.query.paperId);
    const { proxy } = getCurrentInstance();
    
    // 基础数据
    const loading = ref(true);
    const submitting = ref(false);
    const saving = ref(false);
    const paper = ref({});
    const questions = ref([]);
    const answers = reactive({});
    const submitDialogVisible = ref(false);
    const autoSubmitDialogVisible = ref(false);
    const autoSaveTimer = ref(null);
    const saveDebounceTimer = ref(null);
    
    // 计时器相关
    const remainingTime = ref(0);
    const timerInterval = ref(null);
    const warningTime = 300; // 5分钟警告
    const autoSaveInterval = 300 // 自动保存间隔（秒），设置为5分钟
    
    // 富文本编辑器配置
    const editorOptions = {
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline', 'strike'],
          ['blockquote', 'code-block'],
          [{ 'header': 1 }, { 'header': 2 }],
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          [{ 'script': 'sub' }, { 'script': 'super' }],
          [{ 'indent': '-1' }, { 'indent': '+1' }],
          [{ 'direction': 'rtl' }],
          [{ 'size': ['small', false, 'large', 'huge'] }],
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
          [{ 'color': [] }, { 'background': [] }],
          [{ 'font': [] }],
          [{ 'align': [] }],
          ['clean'],
          ['link', 'image']
        ]
      },
      placeholder: '请在此输入您的答案...'
    };
    
    // 分类后的题目
    const singleChoiceQuestions = computed(() => questions.value.filter(q => q.questionType === 0));
    const multiChoiceQuestions = computed(() => questions.value.filter(q => q.questionType === 1));
    const judgmentQuestions = computed(() => questions.value.filter(q => q.questionType === 2));
    const fillBlankQuestions = computed(() => questions.value.filter(q => q.questionType === 3));
    const essayQuestions = computed(() => questions.value.filter(q => q.questionType === 4));
    
    // 所有题目
    const allQuestions = computed(() => questions.value);
    
    // 各题型分数
    const singleChoiceScore = computed(() => {
      return singleChoiceQuestions.value.length > 0 
        ? singleChoiceQuestions.value[0].questionScore 
        : 0;
    });
    
    const multiChoiceScore = computed(() => {
      return multiChoiceQuestions.value.length > 0 
        ? multiChoiceQuestions.value[0].questionScore 
        : 0;
    });
    
    const judgmentScore = computed(() => {
      return judgmentQuestions.value.length > 0 
        ? judgmentQuestions.value[0].questionScore 
        : 0;
    });
    
    const fillBlankScore = computed(() => {
      return fillBlankQuestions.value.length > 0 
        ? fillBlankQuestions.value[0].questionScore 
        : 0;
    });
    
    const essayScore = computed(() => {
      return essayQuestions.value.length > 0 
        ? essayQuestions.value[0].questionScore 
        : 0;
    });

    // 格式化时间
    const formatTime = (seconds) => {
      if (seconds <= 0) return "00:00:00";
      
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const secs = seconds % 60;
      
      return [
        hours.toString().padStart(2, '0'),
        minutes.toString().padStart(2, '0'),
        secs.toString().padStart(2, '0')
      ].join(':');
    };
    
    // 处理填空题
    const processBlankQuestion = (content, questionId) => {
      if (!content) return '';
      
      // 创建填空题答题区域
      // 替换每个下划线序列为输入框
      let blankIndex = 0;
      
      // 在Vue组件中，不能直接修改DOM，所以返回的HTML需要在挂载后处理
      const processedContent = content.replace(/_{8,}/g, () => {
        const blankId = `${questionId}_${blankIndex}`;
        const result = `<input type="text" class="blank-input" 
                        data-blank-index="${blankIndex}" 
                        data-question-id="${questionId}"
                        placeholder="请在此输入答案" />`;
        blankIndex++;
        return result;
      });
      
      // 确保在下一个tick中绑定事件
      nextTick(() => {
        updateFillBlankAnswers();
      });
      
      return processedContent;
    };
    
    // 填空题答案存储
    const fillBlankValues = reactive({});
    
    // 更新填空题输入框
    const updateFillBlankAnswers = () => {
      // 延迟执行，确保DOM已更新
      setTimeout(() => {
        const inputs = document.querySelectorAll('.blank-input');
        // 注释掉频繁输出的日志
        // console.log('找到填空题输入框数量:', inputs.length);
        
        inputs.forEach(input => {
          const questionId = input.getAttribute('data-question-id');
          const blankIndex = input.getAttribute('data-blank-index');
          const blankId = `${questionId}_${blankIndex}`;
          
          // 初始化填空值
          if (fillBlankValues[blankId]) {
            input.value = fillBlankValues[blankId];
          }
          
          // 清除旧的事件监听器，避免重复绑定
          input.removeEventListener('input', handleBlankInput);
          
          // 添加input事件监听器
          input.addEventListener('input', handleBlankInput);
        });
      }, 300);
    };
    
    // 处理填空题输入事件
    const handleBlankInput = (e) => {
      const input = e.target;
      const questionId = input.getAttribute('data-question-id');
      const blankIndex = input.getAttribute('data-blank-index');
      const blankId = `${questionId}_${blankIndex}`;
      
      // 保存填空值
      fillBlankValues[blankId] = input.value;
      
      // 更新answers对象
      if (!answers[questionId]) {
        answers[questionId] = {};
      }
      answers[questionId][blankIndex] = input.value;
      
      // 注释掉频繁输出的日志
      // console.log(`填空题 ${questionId} 的第 ${blankIndex} 空已更新为: ${input.value}`);
    };
    
    // 初始化计时器
    const initTimer = () => {
      // 检查是否已经提交过试卷
      const user = JSON.parse(localStorage.getItem('userInfo') || '{}');
      const userId = user.userId || '';
      const isSubmitted = localStorage.getItem(`exam_submitted_${paperId.value}_${userId}`);
      if (isSubmitted === 'true') {
        console.log('试卷已提交，不初始化计时器');
        return;
      }
      
      // 首先获取服务器当前时间，确保时间计算准确
      getServerTime().then(timeResponse => {
        if (timeResponse.code !== 200) {
          console.error('获取服务器时间失败:', timeResponse.msg);
          // 降级使用本地时间
          initTimerWithProgress(new Date().getTime());
          return;
        }
        
        const serverTimestamp = timeResponse.data.timestamp;
        console.log('获取到服务器时间戳:', serverTimestamp);
        
        // 使用服务器时间初始化计时器
        initTimerWithProgress(serverTimestamp);
      }).catch(error => {
        console.error('获取服务器时间失败:', error);
        // 降级使用本地时间
        initTimerWithProgress(new Date().getTime());
      });
    };
    
    // 使用时间戳初始化计时器和进度
    const initTimerWithProgress = (currentTimestamp) => {
      // 获取已保存的进度
      getAnswerProgress(paperId.value).then(response => {
        if (response.code !== 200) {
          console.error('获取答题进度失败:', response.msg);
          // 修改：没有获取到答题进度时，直接设置为考试时长
          remainingTime.value = paper.value.duration * 60;
          console.log('未获取到答题进度，设置剩余时间为考试时长:', remainingTime.value, '秒');
          // 更新本地存储
          const endTime = Math.floor(Date.now() / 1000) + remainingTime.value;
          localStorage.setItem(`exam_end_time_${paperId.value}`, endTime.toString());
          // 启动计时器
          startTimer();
          return;
        }
        
        if (response.data && response.data.createTime) {
          // 使用创建时间和服务器当前时间计算已用时间
          const createTime = new Date(response.data.createTime).getTime();
          
          // 计算已经使用的时间（秒）- 使用服务器时间确保准确
          const usedTimeInSeconds = Math.floor((currentTimestamp - createTime) / 1000);
          
          console.log('根据服务器时间计算已用时间:', usedTimeInSeconds, '秒');
          
          // 计算剩余时间 = 试卷总时长 - 已用时间
          const totalTimeInSeconds = paper.value.duration * 60;
          remainingTime.value = Math.max(0, totalTimeInSeconds - usedTimeInSeconds);
          
          // 如果剩余时间为0，自动提交
          if (remainingTime.value === 0) {
            autoSubmitDialogVisible.value = true;
            return;
          }
          
          // 将计算后的结束时间保存到localStorage
          const endTime = Math.floor(Date.now() / 1000) + remainingTime.value;
          localStorage.setItem(`exam_end_time_${paperId.value}`, endTime.toString());
        } else {
          // 修改：没有保存的进度或者无法获取创建时间，直接设置为考试时长
            remainingTime.value = paper.value.duration * 60;
          console.log('未获取到进度创建时间，设置剩余时间为考试时长:', remainingTime.value, '秒');
            const endTime = Math.floor(Date.now() / 1000) + remainingTime.value;
            localStorage.setItem(`exam_end_time_${paperId.value}`, endTime.toString());
        }
        
        // 启动计时器
        startTimer();
      }).catch(error => {
        console.error('获取答题进度失败', error);
        
        // 修改：出错时直接使用考试时长
          remainingTime.value = paper.value.duration * 60;
        console.log('获取答题进度出错，设置剩余时间为考试时长:', remainingTime.value, '秒');
          const endTime = Math.floor(Date.now() / 1000) + remainingTime.value;
          localStorage.setItem(`exam_end_time_${paperId.value}`, endTime.toString());
        
        // 启动计时器
        startTimer();
      });
    };
    
    // 启动计时器
    const startTimer = () => {
      // 清除可能存在的旧计时器
      if (timerInterval.value) {
        clearInterval(timerInterval.value);
      }
      
      // 设置每5分钟与服务器同步一次时间的计时器
      const syncTimeInterval = 5 * 60; // 5分钟，单位秒
      let tickCount = 0;
      
      // 设置新的计时器
      timerInterval.value = setInterval(() => {
        if (remainingTime.value > 0) {
          remainingTime.value--;
          tickCount++;
          
          // 每隔autoSaveInterval秒自动保存一次
          if (remainingTime.value % autoSaveInterval === 0 && remainingTime.value > 0) {
            saveProgress();
          }
          
          // 每隔syncTimeInterval秒与服务器同步一次时间
          if (tickCount % syncTimeInterval === 0) {
            syncTimeWithServer();
          }
        } else {
          // 时间到，自动提交
          clearInterval(timerInterval.value);
          autoSubmitDialogVisible.value = true;
        }
      }, 1000);
      
      // 延迟1秒后再执行首次保存，避免与初始化时的保存冲突
      setTimeout(() => {
        // 检查是否已经提交，避免不必要的保存
        const user = JSON.parse(localStorage.getItem('userInfo') || '{}');
        const userId = user.userId || '';
        const isSubmitted = localStorage.getItem(`exam_submitted_${paperId.value}_${userId}`);
        if (isSubmitted !== 'true' && !submitting.value) {
          console.log('延迟1秒后执行首次自动保存');
      saveProgress();
        }
      }, 1000);
      
      // 添加页面可见性变化监听
      document.addEventListener('visibilitychange', handleVisibilityChange);
    };
    
    // 与服务器同步时间，调整剩余时间
    const syncTimeWithServer = () => {
      // 如果正在提交或已提交，不再同步
      if (submitting.value) {
        return;
      }
      
      console.log('开始与服务器同步时间...');
      getServerTime().then(response => {
        if (response.code === 200) {
          const serverTimestamp = response.data.timestamp;
          
          // 获取创建时间
          getAnswerProgress(paperId.value).then(progressResponse => {
            if (progressResponse.code === 200 && progressResponse.data && progressResponse.data.createTime) {
              const createTime = new Date(progressResponse.data.createTime).getTime();
              
              // 使用服务器时间计算已用时间（秒）
              const usedTimeInSeconds = Math.floor((serverTimestamp - createTime) / 1000);
              
              // 计算应该的剩余时间
              const totalTimeInSeconds = paper.value.duration * 60;
              const expectedRemainingTime = Math.max(0, totalTimeInSeconds - usedTimeInSeconds);
              
              // 比较当前剩余时间和预期剩余时间，如果差距超过10秒，则进行调整
              const timeDiff = Math.abs(remainingTime.value - expectedRemainingTime);
              if (timeDiff > 10) {
                console.log(`检测到时间差异（${timeDiff}秒），调整剩余时间: ${remainingTime.value} => ${expectedRemainingTime}`);
                remainingTime.value = expectedRemainingTime;
                
                // 更新localStorage中的结束时间
                const endTime = Math.floor(Date.now() / 1000) + remainingTime.value;
                localStorage.setItem(`exam_end_time_${paperId.value}`, endTime.toString());
              } else {
                console.log('时间同步检查完成，差异在可接受范围内', timeDiff);
              }
            }
          }).catch(error => {
            console.error('同步时获取答题进度失败', error);
          });
        }
      }).catch(error => {
        console.error('同步服务器时间失败', error);
      });
    };
    
    // 处理页面可见性变化
    const handleVisibilityChange = () => {
      // 检查是否已经提交过试卷
      const isSubmitted = localStorage.getItem(`exam_submitted_${paperId.value}_${userStore.id}`);
      if (isSubmitted === 'true') {
        console.log('试卷已提交，不执行页面可见性相关操作');
        return;
      }

      if (document.visibilityState === 'hidden') {
        console.log('页面失去焦点，自动保存进度');
        saveProgress();
      } else if (document.visibilityState === 'visible') {
        console.log('页面重获焦点，同步服务器时间');
        syncTimeWithServer();
      }
    };
    
    // 保存防抖控制
    const isSaving = ref(false);
    
    // 手动保存进度
    const saveProgress = async (isAutoSave = true) => {
      // 如果正在保存或提交试卷，跳过保存
      if (isSaving.value || submitting.value) {
        console.log('正在保存或提交试卷中，跳过保存进度');
        return;
      }
      
      // 检查是否已经提交过试卷
      const isSubmitted = localStorage.getItem(`exam_submitted_${paperId.value}_${userStore.id}`);
      if (isSubmitted === 'true') {
        console.log('试卷已提交，不再保存进度');
        return;
      }
      
      // 清除之前的定时器，实现防抖
      if (saveDebounceTimer.value) {
        clearTimeout(saveDebounceTimer.value);
      }
      
      // 设置新的定时器，延迟300毫秒执行保存
      saveDebounceTimer.value = setTimeout(async () => {
        try {
          isSaving.value = true;
        saving.value = true;
          
          // 再次检查是否已提交（可能在防抖期间状态发生变化）
          if (localStorage.getItem(`exam_submitted_${paperId.value}_${userStore.id}`) === 'true') {
            console.log('防抖期间检测到试卷已提交，取消保存');
            saving.value = false;
            isSaving.value = false;
            return;
          }
        
        // 处理填空题答案
        processBlankAnswersForSubmit();
        
        // 处理单选题和多选题答案
        singleChoiceQuestions.value.forEach(question => {
          if (question.selectedAnswer) {
            answers[question.questionId] = question.selectedAnswer;
          }
        });
        
        multiChoiceQuestions.value.forEach(question => {
          if (question.selectedAnswers && question.selectedAnswers.length > 0) {
            // 确保selectedAnswers是数组
            const answerArray = Array.isArray(question.selectedAnswers) 
              ? question.selectedAnswers 
              : [question.selectedAnswers];
            answers[question.questionId] = answerArray.join(',');
          }
        });
        
          // 添加剩余时间信息到保存请求中
        const response = await saveAnswerProgress({
          paperId: paperId.value,
            answers: answers,
            remainingTime: remainingTime.value // 添加剩余时间信息，让后端可以更精确地记录
        });
        
        if (response.code === 200) {
          ElMessage.success('保存进度成功');
        } else {
            // 只有在非"数据正在处理"错误时显示错误消息
            if (response.msg && !response.msg.includes('数据正在处理')) {
          ElMessage.error(response.msg || '保存失败');
            } else {
              console.log('保存进度被防重复提交机制拦截，稍后将重试');
        }
          }
      } catch (error) {
          // 只有在非"数据正在处理"错误时显示错误消息
          if (!error.message || !error.message.includes('数据正在处理')) {
        console.error('保存进度失败:', error);
        ElMessage.error('保存失败，请重试');
          } else {
            console.log('保存进度被防重复提交机制拦截，稍后将重试');
          }
        } finally {
        saving.value = false;
          isSaving.value = false;
      }
      }, 300);
    };
    
    // 处理填空题答案以便提交
    const processBlankAnswersForSubmit = () => {
      fillBlankQuestions.value.forEach(question => {
        const questionId = question.questionId;
        const blankAnswers = {};
        
        // 获取题目包含的空的数量
        // 通过查找题目内容中的下划线序列来确定有多少个填空
        const content = question.questionContent || '';
        const blankCount = (content.match(/_{8,}/g) || []).length;
        
        // 先初始化所有空为"学生未作答"
        for (let i = 0; i < blankCount; i++) {
          blankAnswers[i] = "学生未作答";
        }
        
        // 收集该题目的所有填空答案
        Object.keys(fillBlankValues).forEach(key => {
          if (key.startsWith(`${questionId}_`)) {
            const blankIndex = key.split('_')[1];
            const value = fillBlankValues[key];
            // 修改：如果学生实际输入了答案或使用空字符串直接覆盖默认值
            if (value !== undefined) {
              // 只有当值不是空字符串时才使用学生输入的值，否则保持为"学生未作答"
              if (value && value.trim() !== '') {
                blankAnswers[blankIndex] = value;
              }
            }
          }
        });
        
        // 更新到answers对象
        if (Object.keys(blankAnswers).length > 0) {
          answers[questionId] = blankAnswers;
        }
      });
    };
    
    // 添加排序多选题答案的函数
    const sortMultiChoiceAnswer = (answerArray) => {
      if (!answerArray || answerArray.length === 0) return [];
      return [...answerArray].sort();
    };
    
    // 检查试卷是否已提交
    const checkSubmitStatus = async () => {
      try {
        const res = await getExamSubmitStatus(paperId.value);
        if (res.code === 200 && res.data === true) {
          ElMessage.warning("该试卷已提交，不能重复答题");
          
          // 清理所有监听器和计时器
          clearAllListeners();
          
          // 关闭当前标签页并返回列表页
          proxy.$tab.closePage();
          router.replace("/task/examination");
          return true;
        }
        return false;
      } catch (error) {
        console.error("检查提交状态失败:", error);
        return false;
      }
    };
    
    // 提交答案
    const submitAnswer = async () => {
      // 检查试卷是否已提交
      const isSubmitted = await checkSubmitStatus();
      if (isSubmitted) {
        return;
      }
      
      // 打开确认对话框
      submitDialogVisible.value = true;
    };
    
    // 自动提交确认
    const confirmAutoSubmit = () => {
      autoSubmitDialogVisible.value = false;
      
      // 清除计时器和事件监听
      if (timerInterval.value) {
        clearInterval(timerInterval.value);
        timerInterval.value = null;
      }
      
      // 移除页面可见性监听
      document.removeEventListener('visibilitychange', handleVisibilityChange);
      
      confirmSubmit();
    };
    
    // 确认提交
    const confirmSubmit = () => {
      if (submitting.value) return;
      
      submitting.value = true;
      submitDialogVisible.value = false;
      
      // 清除计时器和事件监听
      if (timerInterval.value) {
        clearInterval(timerInterval.value);
        timerInterval.value = null;
      }
      
      // 清除所有保存中的防抖定时器
      if (saveDebounceTimer.value) {
        clearTimeout(saveDebounceTimer.value);
        saveDebounceTimer.value = null;
      }
      
      // 移除页面可见性监听
      document.removeEventListener('visibilitychange', handleVisibilityChange);
      
      // 处理单选题和多选题答案
        singleChoiceQuestions.value.forEach(question => {
          if (question.selectedAnswer) {
            answers[question.questionId] = question.selectedAnswer;
          }
        });
        
        multiChoiceQuestions.value.forEach(question => {
          if (question.selectedAnswers && question.selectedAnswers.length > 0) {
            // 确保selectedAnswers是数组
            const answerArray = Array.isArray(question.selectedAnswers) 
              ? question.selectedAnswers 
              : [question.selectedAnswers];
            // 对多选题答案进行排序，确保以A,B,C,D的顺序存储
            const sortedAnswerArray = sortMultiChoiceAnswer(answerArray);
            answers[question.questionId] = sortedAnswerArray.join(',');
          }
        });
        
        // 处理填空题答案
        processBlankAnswersForSubmit();
        
        // 获取用户信息
        const userId = userStore.id;
        const userName = userStore.name; // 获取用户名（学号）
      console.log('确认提交试卷，用户ID:', userId, '用户名:', userName);
        
        // 构建提交数据
        const submitData = {
          paperId: paperId.value,
          userId: Number(userId), // 确保userId为数字
          studentNumber: userStore.name === 'admin' ? '1000000001' : userStore.studentNumber, // 添加学号，用于正确写入student_number字段
          answers: answers,
          remainingTime: formatTimeString(remainingTime.value) // 添加剩余时间，格式为HH:mm:ss
        };
        
      // 在提交前，先主动清理进度记录
      console.log('提交前，主动清理进度记录');
      saveAnswerProgress({
        paperId: paperId.value,
        answers: {},
        isSubmitted: true // 标记为已提交，触发后端删除操作
      }).then(() => {
        console.log('清理进度记录成功，开始提交答案');
        // 清理成功后提交答案
        submitExamData();
      }).catch(() => {
        // 即使清理失败，也继续提交
        console.log('清理进度记录失败，继续提交答案');
        submitExamData();
      });
    };
    
    // 提取提交答案的逻辑为独立函数
    const submitExamData = async () => {
      try {
        submitting.value = true;
        const submitData = constructSubmitData();
        const response = await submitExamAnswer(submitData);
        if (response.code === 200) {
          ElMessage.success("试卷提交成功");
          // 清除自动保存定时器
          if (autoSaveTimer.value) {
            clearInterval(autoSaveTimer.value);
          }
          
          // 关闭当前标签页
          proxy.$tab.closePage();
          
          // 跳转到考试列表页面
          router.push("/task/examination");
        } else {
          ElMessage.error(response.msg || "提交失败");
        }
      } catch (error) {
        console.error("提交失败:", error);
        ElMessage.error("提交失败，请稍后重试");
      } finally {
        submitting.value = false;
      }
    };
    
    // 构建提交数据
    const constructSubmitData = () => {
      // 处理填空题答案
      processBlankAnswersForSubmit();
      
      // 处理单选题和多选题答案
      singleChoiceQuestions.value.forEach(question => {
        if (question.selectedAnswer) {
          answers[question.questionId] = question.selectedAnswer;
        }
      });
        
      multiChoiceQuestions.value.forEach(question => {
        if (question.selectedAnswers && question.selectedAnswers.length > 0) {
          // 确保selectedAnswers是数组
          const answerArray = Array.isArray(question.selectedAnswers) 
            ? question.selectedAnswers 
            : [question.selectedAnswers];
          // 对多选题答案进行排序，确保以A,B,C,D的顺序存储
          const sortedAnswerArray = sortMultiChoiceAnswer(answerArray);
          answers[question.questionId] = sortedAnswerArray.join(',');
        }
      });
      
      // 构建提交数据
      return {
        paperId: paperId.value,
        userId: Number(userStore.id),
        studentNumber: userStore.name === 'admin' ? '1000000001' : userStore.studentNumber,
        answers: answers,
        remainingTime: formatTimeString(remainingTime.value)
      };
    };
    
    // 打印调试信息
    const logDebugInfo = () => {
      console.log('==== 试卷答题页面调试信息 ====');
      console.log('试卷数据:', paper.value);
      console.log('所有题目:', questions.value);
      console.log('单选题:', singleChoiceQuestions.value);
      console.log('多选题:', multiChoiceQuestions.value);
      console.log('判断题:', judgmentQuestions.value);
      console.log('填空题:', fillBlankQuestions.value);
      console.log('简答题:', essayQuestions.value);
      console.log('当前答案:', answers);
      console.log('============================');
    };

    // 获取试卷数据
    const getPaper = async () => {
      loading.value = true;
      
      try {
        // 先检查试卷是否已提交
        const isSubmitted = await checkSubmitStatus();
        if (isSubmitted) {
          loading.value = false;
          return;
        }
        
        const response = await getPaperForExam(paperId.value);
        if (response.code === 200) {
          // 处理试卷数据
        paper.value = response.data;
        
          // 初始化题目列表
          const processedQuestions = [];
          
          // 处理题目数据
        if (response.data.questions && response.data.questions.length > 0) {
            // 解析API返回的questions数组，每个元素包含question对象
            response.data.questions.forEach(item => {
              if (item.question) {
                // 设置问题类型和分数
                const questionData = {
                  ...item.question,
                  questionScore: item.questionScore || 0,
                  questionOrder: item.questionOrder || 0,
                  questionType: item.question.questionType,
                  options: item.question.options || []
                };
                
                // 根据题目类型做不同处理
                if (questionData.questionType === 0 || questionData.questionType === 1) {
                  // 单选题和多选题，确保选项有正确的格式
                  if (questionData.options && questionData.options.length > 0) {
                    // 转换选项格式，添加optionKey属性用于v-model绑定
                    questionData.options = questionData.options.map(opt => ({
                      ...opt,
                      optionKey: opt.optionLabel
                    }));
                  }
                  
                  // 初始化选择 
                  if (questionData.questionType === 0) {
                    // 单选题初始化选择
                    questionData.selectedAnswer = '';
              } else {
                    // 多选题初始化选择
                    questionData.selectedAnswers = [];
                  }
                }
                
                // 添加到处理后的题目列表
                processedQuestions.push(questionData);
              }
            });
          }
          
          console.log('处理后的题目列表:', processedQuestions);
          questions.value = processedQuestions;
        
        // 初始化计时器
        initTimer();
        
        // 加载已保存的答案
        loadSavedAnswers();
            
          // 下一个tick渲染数学公式
          nextTick(() => {
            renderMathJax();
          });
          
          // 设置自动保存定时器（仅每5分钟保存一次）
          autoSaveTimer.value = setInterval(() => {
            saveProgress(false);
          }, 5 * 60 * 1000); // 5分钟
        
        loading.value = false;
        } else {
          // 处理错误响应
          ElMessage.error(response.msg || '获取试卷失败');
          setTimeout(() => {
            router.replace('/task/examination');
          }, 1500);
        loading.value = false;
        }
      } catch (error) {
        console.error('获取试卷失败:', error);
        ElMessage.error('获取试卷失败，请重试');
        loading.value = false;
        setTimeout(() => {
          router.replace('/task/examination');
        }, 1500);
      }
    };
    
    // 加载已保存的答案
    const loadSavedAnswers = () => {
      getAnswerProgress(paperId.value).then(response => {
        if (response.data && response.data.answers) {
          // 恢复各种题型的答案
          const savedAnswers = response.data.answers;
          
          // 填充answers对象
          Object.keys(savedAnswers).forEach(questionId => {
            const answer = savedAnswers[questionId];
            answers[questionId] = answer;
            
            // 找到对应的题目
            const question = questions.value.find(q => q.questionId === questionId);
            if (question) {
              switch (question.questionType) {
                case 0: // 单选题
                  question.selectedAnswer = answer;
                  break;
                case 1: // 多选题
                  if (typeof answer === 'string') {
                    question.selectedAnswers = answer.split(',').filter(Boolean);
                    // 注释掉频繁输出的日志
                    // console.log('恢复多选题答案', questionId, question.selectedAnswers);
                  }
                  break;
                case 3: // 填空题
                  if (typeof answer === 'object') {
                    Object.keys(answer).forEach(blankIndex => {
                      const blankId = `${questionId}_${blankIndex}`;
                      // 修改：只有当答案不是"学生未作答"时才设置填空值
                      const blankAnswer = answer[blankIndex];
                      if (blankAnswer && blankAnswer !== "学生未作答") {
                        fillBlankValues[blankId] = blankAnswer;
                      } else {
                        // 对于未作答的空，设置为空字符串
                        fillBlankValues[blankId] = "";
                      }
                    });
                  }
                  break;
              }
            }
          });
          
          // 更新DOM中的填空框
          updateFillBlankAnswers();
        }
      }).catch(error => {
        console.error('加载已保存答案失败', error);
        // 不显示错误消息，因为可能是第一次答题
      });
    };
    
    // 修改MathJax加载方式
    const loadMathJax = () => {
      return new Promise((resolve) => {
        if (window.MathJax) {
          // 如果已经加载，重新配置并尝试渲染
          try {
            if (window.MathJax.typesetPromise) {
              window.MathJax.typesetPromise();
            } else if (window.MathJax.typeset) {
              window.MathJax.typeset();
            }
          } catch (e) {
            console.error('MathJax已加载但渲染失败:', e);
          }
          resolve(window.MathJax);
          return;
        }
        
        // 先创建配置
        window.MathJax = {
          tex: {
            inlineMath: [['$', '$'], ['\\(', '\\)']],
            displayMath: [['$$', '$$'], ['\\[', '\\]']]
          },
          svg: {
            fontCache: 'global'
          },
          startup: {
            ready: () => {
              console.log('MathJax is ready');
              window.MathJax.startup.defaultReady();
              resolve(window.MathJax);
            }
          }
        };
        
        // 然后加载脚本
        const script = document.createElement('script');
        script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
        script.async = true;
        script.onload = () => {
          console.log('MathJax脚本已加载');
        };
        script.onerror = (e) => {
          console.error('MathJax加载失败:', e);
        };
        document.head.appendChild(script);
      });
    };

    // 渲染数学公式
    const renderMathJax = async () => {
      await nextTick();
      try {
        const mathJax = await loadMathJax();
        console.log('MathJax已加载完成');
        
        await nextTick();
        
        if (mathJax.typesetPromise) {
          await mathJax.typesetPromise();
          console.log('使用typesetPromise方法渲染公式完成');
        } else if (mathJax.typeset) {
          mathJax.typeset();
          console.log('使用typeset方法渲染公式完成');
        } else {
          console.error('找不到MathJax的渲染方法');
        }
      } catch (error) {
        console.error('MathJax渲染错误:', error);
      }
    };

    // 添加计算各题型总分的计算属性，放在对应位置
    const singleChoiceTotal = computed(() => {
      return singleChoiceQuestions.value.reduce((sum, q) => sum + parseFloat(q.questionScore || 0), 0).toFixed(2);
    });

    const multiChoiceTotal = computed(() => {
      return multiChoiceQuestions.value.reduce((sum, q) => sum + parseFloat(q.questionScore || 0), 0).toFixed(2);
    });

    const judgmentTotal = computed(() => {
      return judgmentQuestions.value.reduce((sum, q) => sum + parseFloat(q.questionScore || 0), 0).toFixed(2);
    });

    const fillBlankTotal = computed(() => {
      return fillBlankQuestions.value.reduce((sum, q) => sum + parseFloat(q.questionScore || 0), 0).toFixed(2);
    });

    const essayTotal = computed(() => {
      return essayQuestions.value.reduce((sum, q) => sum + parseFloat(q.questionScore || 0), 0).toFixed(2);
    });

    // 格式化时间为HH:mm:ss格式
    const formatTimeString = (seconds) => {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const secs = seconds % 60;
      
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    };

    // 处理页面关闭事件
    const handleBeforeUnload = async (e) => {
      // 检查试卷是否已提交
      try {
        const res = await getExamSubmitStatus(paperId.value);
        // 如果没提交且不是在提交过程中，提示用户
        if (res.code === 200 && !res.data && !submitting.value) {
          e.preventDefault();
          e.returnValue = '您有未提交的答案，确定要离开吗？';
        }
      } catch (error) {
        console.error('检查提交状态失败:', error);
        // 出错时默认提示用户
        e.preventDefault();
        e.returnValue = '您有未提交的答案，确定要离开吗？';
      }
    };

    // 清理所有监听器和计时器
    const clearAllListeners = () => {
      // 清除计时器
      if (timerInterval.value) {
        clearInterval(timerInterval.value);
        timerInterval.value = null;
      }
      
      // 清除自动保存定时器
      if (autoSaveTimer.value) {
        clearInterval(autoSaveTimer.value);
        autoSaveTimer.value = null;
      }
      
      // 清除防抖定时器
      if (saveDebounceTimer.value) {
        clearTimeout(saveDebounceTimer.value);
        saveDebounceTimer.value = null;
      }
      
      // 移除页面可见性变化监听
      document.removeEventListener('visibilitychange', handleVisibilityChange);
      
      // 移除页面关闭提醒
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };

    // 修改组件挂载逻辑
    onMounted(async () => {
      if (!paperId.value) {
        ElMessage.error('试卷ID不能为空');
        router.push('/task/examination');
        return;
      }
      
      // 添加页面关闭提醒
      window.addEventListener('beforeunload', handleBeforeUnload);
      
      // 获取试卷和题目
      await getPaper();
    });
    
    // 修改组件销毁前的清理逻辑
    onBeforeUnmount(async () => {
      try {
        // 检查是否已经提交过试卷
        const res = await getExamSubmitStatus(paperId.value);
        if (res.code === 200 && res.data) {
          console.log('试卷已提交，不执行清理和自动保存');
          clearAllListeners();
          return;
        }
        
        // 如果还没提交，且不是在提交过程中，则保存一次进度
      if (!submitting.value) {
          await saveProgress(false);
        }
      } catch (error) {
        console.error('组件销毁前检查失败:', error);
      } finally {
        // 清理所有监听器和计时器
        clearAllListeners();
      }
    });
    
    const userStore = useUserStore()
    
    return {
      paper,
      questions,
      allQuestions,
      answers,
      loading,
      submitting,
      saving,
      remainingTime,
      warningTime,
      submitDialogVisible,
      autoSubmitDialogVisible,
      singleChoiceQuestions,
      multiChoiceQuestions,
      judgmentQuestions,
      fillBlankQuestions,
      essayQuestions,
      singleChoiceScore,
      multiChoiceScore,
      judgmentScore,
      fillBlankScore,
      essayScore,
      singleChoiceTotal,
      multiChoiceTotal,
      judgmentTotal,
      fillBlankTotal,
      essayTotal,
      fillBlankValues,
      editorOptions,
      formatTime,
      processBlankQuestion,
      submitAnswer,
      confirmSubmit,
      saveProgress,
      confirmAutoSubmit,
      renderMathJax,
      userStore
    };
  }
};
</script>

<style>
/* 全局样式，确保MathJax公式正确显示 */
.app-container .MathJax {
  display: inline-block !important;
  margin: 0 3px;
  vertical-align: middle;
}

.app-container .katex {
  font-size: 1.1em;
}

/* 富文本编辑器样式 */
.ql-editor {
  min-height: 150px;
  font-size: 14px;
}

.ql-toolbar {
  background-color: #f8f8f8;
}

.ql-container {
  background-color: #fff;
}
</style>

<style scoped>
.question-type {
  margin-right: 10px;
  color: #409EFF;
}
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.paper-info {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.paper-title {
  text-align: center;
  font-size: 22px;
  margin-bottom: 15px;
}

.paper-metadata {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}

.metadata-item {
  margin: 0 15px;
  font-size: 14px;
}

.score-value {
  color: #f56c6c;
  font-weight: bold;
}

.timer-container {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}

.timer {
  padding: 8px 16px;
  border-radius: 4px;
  background-color: #ecf5ff;
  color: #409eff;
  display: inline-flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.timer-warning {
  background-color: #fff6f7;
  color: #f56c6c;
  animation: blink 1s infinite;
}

@keyframes blink {
  50% {
    opacity: 0.7;
  }
}

.time-text {
  margin-left: 8px;
}

.paper-content {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.question-section {
  margin-bottom: 30px;
}

.section-title {
  padding: 10px;
  background-color: #ecf5ff;
  border-left: 5px solid #409EFF;
  margin-bottom: 20px;
  font-weight: bold;
}

.question-item {
  margin-bottom: 25px;
  padding-bottom: 20px;
  border-bottom: 1px dashed #ebeef5;
}

.question-header {
  display: flex;
  margin-bottom: 10px;
  align-items: flex-start;
}

.question-index {
  flex-shrink: 0;
  margin-right: 5px;
  font-weight: bold;
}

.question-content {
  flex-grow: 1;
  margin-right: 10px;
}

.question-score {
  margin-left: 10px;
  color: #e42e2e;
}

.options-container {
  margin-left: 20px;
  margin-top: 15px;
}

.option-row {
  display: flex;
  margin-bottom: 12px;
  align-items: flex-start;
}

.option-label {
  font-weight: bold;
  margin-right: 5px;
  min-width: 20px;
}

.option-content {
  white-space: normal;
}

.essay-answer {
  margin-left: 20px;
  margin-top: 15px;
}

.paper-footer {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding: 20px 0;
}

.paper-footer .el-button {
  margin: 0 10px;
  min-width: 120px;
}

:deep(.blank-input) {
  border: none;
  border-bottom: 1px solid #409eff;
  background-color: #f5f7fa;
  padding: 5px 8px;
  margin: 0 5px;
  min-width: 100px;
  text-align: center;
  outline: none;
  transition: all 0.3s;
}

:deep(.blank-input:focus) {
  border-bottom: 2px solid #409eff;
  background-color: #ecf5ff;
}

:deep(.el-radio) {
  width: 100%;
  display: flex;
  margin-bottom: 15px;
  align-items: flex-start;
}

:deep(.el-checkbox) {
  width: 100%;
  display: flex;
  margin-bottom: 15px;
  align-items: flex-start;
}

.options-container {
  margin-top: 15px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.option-item {
  display: flex;
  align-items: flex-start;
  padding: 5px 0;
}

.option-key {
  margin-right: 8px;
  font-weight: bold;
  min-width: 25px;
}

.option-content {
  flex: 1;
  line-height: 1.5;
}

:deep(.el-radio__label),
:deep(.el-checkbox__label) {
  display: flex;
  align-items: flex-start;
  white-space: normal;
  line-height: 1.5;
}

:deep(.el-radio__inner),
:deep(.el-checkbox__inner) {
  margin-top: 3px;
}

:deep(.option-content p) {
  margin: 0;
  display: inline;
}

/* 保存进度按钮样式 */
.save-progress-btn {
  transition: none !important;
}

.save-progress-btn:active {
  transform: none !important;
}
</style>
